package swing.customComp;

import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

public class JTextFieldHintListener implements FocusListener {

    private String hintText; //默认提示内容
    private HintJTextField hintJTextField; //输入框的引用

    public JTextFieldHintListener(HintJTextField hintJTextField, String hintText) {
        this.hintJTextField = hintJTextField;
        this.hintText = hintText;
        hintJTextField.setText(hintText);
        hintJTextField.setForeground(Color.GRAY);
    }

    @Override
    public void focusGained(FocusEvent e) {
        //获取焦点时，清空提示内容
        String temp = hintJTextField.getRealText();
        hintJTextField.setHint(false);
        if(temp.equals(hintText)) {
            hintJTextField.setText("");
            hintJTextField.setForeground(Color.BLACK);
        }

    }

    @Override
    public void focusLost(FocusEvent e) {
        //失去焦点时，没有输入内容，显示提示内容
        String temp = hintJTextField.getRealText();
        if(temp.equals("")) {
            hintJTextField.setHint(true);
            hintJTextField.setForeground(Color.GRAY);
            hintJTextField.setText(hintText);
        }

    }

}
